<script setup lang="ts">
import { useRequest } from "alova/client";

import type { ArticleEntity } from "@/api/globals";

// const articles = ref<any[]>([]);
// const loading = ref(true);

// 模拟 API 请求（替换为真实调用）
// const fetchArticles = async () => {
//     try {
//         // const res = await getArticles()
//         // articles.value = res.data

//         // 模拟数据（与你 seed 数据一致）
//         articles.value = [
//             {
//                 id: 1,
//                 title: "如何高效学习编程？这 5 个方法你一定要知道",
//                 content: "<p>在当今数字化时代，编程已成为一项核心技能...</p>",
//                 excerpt: "掌握高效学习方法，让你的编程之路事半功倍。",
//                 coverImage: "https://picsum.photos/800/400?random=1",
//                 author: "李明",
//                 categoryId: 1,
//                 views: 1240,
//                 createdAt: "2025-10-27T10:00:00.000Z",
//                 updatedAt: "2025-10-27T10:00:00.000Z",
//                 isDeleted: false,
//                 deletedAt: null,
//                 Category: { id: 1, name: "推荐" }
//             },
//             {
//                 id: 2,
//                 title: "某顶流明星官宣恋情，粉丝炸锅！",
//                 content: "<p>今日凌晨，知名艺人XXX在社交平台发布长文...</p>",
//                 excerpt: "恋情曝光引发全网热议，相关话题阅读量破10亿。",
//                 coverImage: "https://picsum.photos/800/400?random=3",
//                 author: "娱乐前线",
//                 categoryId: 2,
//                 views: 3850000,
//                 createdAt: "2025-10-28T01:15:00.000Z",
//                 updatedAt: "2025-10-28T01:15:00.000Z",
//                 isDeleted: false,
//                 deletedAt: null,
//                 Category: { id: 2, name: "热点" }
//             },
//             {
//                 id: 3,
//                 title: "国产大模型“星辰”发布，性能对标GPT-4",
//                 content: "<p>今日，国内AI公司DeepMind China发布全新大语言模型...</p>",
//                 excerpt: "国产大模型再突破，AI竞赛进入新阶段。",
//                 coverImage: "",
//                 author: "AI前沿",
//                 categoryId: 4,
//                 views: 98000,
//                 createdAt: "2025-10-26T14:30:00.000Z",
//                 updatedAt: "2025-10-26T14:30:00.000Z",
//                 isDeleted: false,
//                 deletedAt: null,
//                 Category: { id: 4, name: "科技" }
//             },
//             {
//                 id: 4,
//                 title: "全国人大常委会通过新修订的《网络安全法》",
//                 content: "<p>2025年10月25日，十四届全国人大常委会第十二次会议...</p>",
//                 excerpt: "新法强化数据安全与个人信息保护。",
//                 coverImage: "https://picsum.photos/800/400?random=11",
//                 author: "法治中国",
//                 categoryId: 5,
//                 views: 45600,
//                 createdAt: "2025-10-25T09:20:00.000Z",
//                 updatedAt: "2025-10-25T09:20:00.000Z",
//                 isDeleted: false,
//                 deletedAt: null,
//                 Category: { id: 5, name: "时政" }
//             }
//         ];
//     } catch (error) {
//         console.error("Failed to fetch articles", error);
//     } finally {
//         loading.value = false;
//     }
// };

const props = defineProps<{
    categoryId: number;
}>();

const curPage = ref(1);
const isShowMoreBtn = ref(true);
const loadedMoreData = ref<ArticleEntity[]>([]);

const { data, loading } = useRequest(() => Apis.Article.page({ params: { size: 5, current: curPage.value } }));
const articles = computed(() => [...data.value?.data?.list, ...loadedMoreData.value]);

const handleLoadMore = async () => {
    const { data } = await Apis.Article.page({
        params: {
            size: 5,
            current: curPage.value + 1,
            categoryId: props.categoryId
        }
    });
    curPage.value++;
    loadedMoreData.value = data.list;
    if (data.list.length < 5) {
        isShowMoreBtn.value = false;
    }
};

watch(
    () => props.categoryId,
    async newValue => {
        const res = await Apis.Article.page({
            params: {
                size: 5,
                current: 1,
                categoryId: newValue
            }
        });
        data.value.data.list = [] as any;
        loadedMoreData.value = res.data.list;
        if (res.data.list.length < 5) {
            isShowMoreBtn.value = false;
        }
    }
);

// 格式化时间（如“2小时前”）
const formatTimeAgo = (dateStr: string): string => {
    const now = new Date();
    const past = new Date(dateStr);
    const diffMs = now.getTime() - past.getTime();
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffHours < 1) return "刚刚";
    if (diffHours < 24) return `${diffHours}小时前`;
    if (diffDays < 7) return `${diffDays}天前`;
    return past.toLocaleDateString("zh-CN");
};

// 格式化阅读量（如 1.2万）
const formatViews = (views: number): string => {
    if (views >= 10000) {
        return (views / 10000).toFixed(1) + "万";
    }
    return views.toString();
};

// 分类颜色映射（可扩展）
const getCategoryColor = (categoryId: number): string => {
    const colors: Record<number, string> = {
        1: "bg-blue-100 text-blue-800", // 推荐
        2: "bg-red-100 text-red-800", // 热点
        3: "bg-green-100 text-green-800", // 财经
        4: "bg-purple-100 text-purple-800", // 科技
        5: "bg-yellow-100 text-yellow-800" // 时政
    };
    return colors[categoryId] || "bg-gray-100 text-gray-800";
};
</script>

<template>
    <div class="mx-auto max-w-6xl px-4 py-6">
        <h1 class="mb-6 text-2xl font-bold text-gray-900">最新文章</h1>

        <div v-if="loading" class="py-10 text-center">
            <p class="text-gray-500">加载中...</p>
        </div>

        <div v-else class="space-y-8">
            <template v-if="articles.length === 0">
                <a-empty />
            </template>
            <article
                v-else
                v-for="article in articles"
                :key="article.id"
                class="group cursor-pointer"
                @click="$router.push(`/article/${article.id}`)"
            >
                <!-- 有封面图：左右布局 -->
                <div v-if="article.coverImage" class="flex min-h-48 flex-col gap-6 md:flex-row">
                    <div class="md:w-2/3">
                        <div class="mb-2 flex items-center gap-2">
                            <span
                                class="rounded-full px-2 py-1 text-xs font-medium"
                                :class="getCategoryColor(article.categoryId)"
                            >
                                {{ article.Category.name }}
                            </span>
                            <span class="text-xs text-gray-500">
                                {{ formatTimeAgo(article.createdAt) }}
                            </span>
                        </div>
                        <h2
                            class="mb-2 line-clamp-2 text-xl font-bold text-gray-900 transition-colors group-hover:text-blue-600"
                        >
                            {{ article.title }}
                        </h2>
                        <p class="mb-3 line-clamp-2 text-gray-600">
                            {{ article.excerpt }}
                        </p>
                        <div class="flex items-center text-sm text-gray-500">
                            <span>{{ article.author }}</span>
                            <span class="mx-2">•</span>
                            <span>{{ formatViews(article.views) }}阅读</span>
                        </div>
                    </div>
                    <div class="flex-shrink-0 md:w-1/3">
                        <img
                            :src="article.coverImage"
                            :alt="article.title"
                            class="h-48 w-full rounded-lg object-cover shadow-sm transition-shadow group-hover:shadow-md"
                        />
                    </div>
                </div>

                <!-- 无封面图：纯文本布局 -->
                <div v-else class="min-h-48">
                    <div class="mb-2 flex items-center gap-2">
                        <span
                            class="rounded-full px-2 py-1 text-xs font-medium"
                            :class="getCategoryColor(article.categoryId)"
                        >
                            {{ article.Category.name }}
                        </span>
                        <span class="text-xs text-gray-500">
                            {{ formatTimeAgo(article.createdAt) }}
                        </span>
                    </div>
                    <h2
                        class="mb-2 line-clamp-2 text-xl font-bold text-gray-900 transition-colors group-hover:text-blue-600"
                    >
                        {{ article.title }}
                    </h2>
                    <p class="mb-3 line-clamp-2 text-gray-600">
                        {{ article.excerpt }}
                    </p>
                    <div class="flex items-center text-sm text-gray-500">
                        <span>{{ article.author }}</span>
                        <span class="mx-2">•</span>
                        <span>{{ formatViews(article.views) }}阅读</span>
                    </div>
                </div>
            </article>

            <!-- 分页（可选） -->
            <div v-if="articles.length > 0 && isShowMoreBtn" class="mt-8 flex justify-center">
                <a-button type="primary" @click="handleLoadMore"> 加载更多 </a-button>
            </div>
        </div>
    </div>
</template>
